package com.core.listener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class RedisConnectionListener implements ApplicationListener<ApplicationReadyEvent> {

    private static final Logger logger = LoggerFactory.getLogger(RedisConnectionListener.class);

    // 注入Spring自动配置的Redis连接工厂
    @Resource
    private RedisConnectionFactory redisConnectionFactory;

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        // 应用就绪后，测试Redis连接
        testRedisConnection();
    }

    /**
     * 测试Redis连接：获取连接并执行PING命令
     */
    private void testRedisConnection() {
        RedisConnection connection = null;
        try {
            // 从连接工厂获取连接
            connection = redisConnectionFactory.getConnection();
            // 执行PING命令（Redis服务器会返回"PONG"）
            String pingResult = connection.ping();
            // 若返回PONG，说明连接成功
            if ("PONG".equals(pingResult)) {
                logger.info("✅ Redis连接成功！");
            } else {
                logger.error("❌ Redis连接异常：PING命令返回非预期结果：{}", pingResult);
            }
        } catch (Exception e) {
            // 捕获所有连接相关异常（如连接超时、拒绝连接、密码错误等）
            logger.error("❌ Redis连接失败！原因：{}", e.getMessage(), e);
        } finally {
            // 释放连接（若使用连接池，需归还连接）
            if (connection != null) {
                connection.close();
            }
        }
    }
}
